<template>
  <!-- 工序责任设置表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      :width="!props.isReadonly ? '700px' : '800px'"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="60"
        v-show="!props.isReadonly"
      >
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div>
          <el-row>
            <el-form-item label="工序" prop="processId" style="width: 100%">
              <el-select
                v-model="formData.processId"
                v-if="!props.isReadonly"
                placeholder="请选择工序"
                clearable
                @change="changeProcess"
              >
                <el-option
                  v-for="item in processList"
                  :key="item.id"
                  :label="`${item.processCode}`"
                  :value="item.id"
                />
              </el-select>
              <span v-else>{{ formData.processId }}</span>
            </el-form-item>
          </el-row>
        </div>

        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
          v-if="!props.isReadonly"
        >
          <h4 class="mb-[20px] mt-[20px]">上级领导人列表</h4>
          <el-button
            type="success"
            plain
            @click="handleAddLeader"
            v-if="!props.isReadonly"
          >
            <i-ep-plus />
            新增
          </el-button>
        </div>

        <div class="formTable">
          <el-table
            :data="tableLeader"
            style="width: 100%"
            :key="Math.random"
            border
            v-if="!props.isReadonly"
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />
            <el-table-column
              label="领导人"
              props="roleName"
              min-width="150"
              align="center"
            >
              <template #default="{ $index, row }">
                <!-- <el-form-item
                  :prop="'details.' + $index + '.parameterDesc'"
                  :rules="rules.sonparameterDesc"
                  label-width="0"
                > -->
                <!-- <el-input
                    v-if="!props.isReadonly"
                    v-model="row.parameterDesc"
                    placeholder="请输入参数描述"
                    clearable
                  /> -->
                <span>{{ row.roleName }}</span>
                <!-- </el-form-item> -->
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  @click.stop="handleDeleteLeader(scope.$index)"
                  ><i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
          v-if="!props.isReadonly"
        >
          <h4 class="mb-[20px] mt-[20px]">责任人列表</h4>
          <el-button
            type="success"
            plain
            @click="handleAddPerson"
            v-if="!props.isReadonly"
          >
            <i-ep-plus />
            新增
          </el-button>
        </div>
        <div class="formTable">
          <el-table
            :data="tablePerson"
            style="width: 100%"
            :key="Math.random"
            border
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />
            <el-table-column
              label="责任人"
              props="roleName"
              min-width="150"
              align="center"
            >
              <template #default="{ $index, row }">
                <!-- <el-form-item
                  :prop="'details.' + $index + '.parameterDesc'"
                  :rules="rules.sonparameterDesc"
                  label-width="0"
                > -->
                <!-- <el-input
                    v-if="!props.isReadonly"
                    v-model="row.parameterDesc"
                    placeholder="请输入参数描述"
                    clearable
                  /> -->
                <span>{{ row.roleName }}</span>
                <!-- </el-form-item> -->
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  @click.stop="handleDeletePerson(scope.$index)"
                  ><i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
      <el-descriptions
        class="margin-top"
        title=""
        :column="2"
        size="large"
        border
        v-show="props.isReadonly"
      >
        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">工序</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.processCode }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">上级领导人列表</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.leaderRoleList }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">责任人列表</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.responsibleRoleList }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    <!-- 设备选择 -->
    <psmprocessduty-select
      :visible="selectDialogLeader.visible"
      :data="breakListLeader"
      :title="selectDialogLeader.title"
      @change-visible-leader="changeVisibleLeader"
    />
    <psmprocessduty-select
      :visible="selectDialogPerson.visible"
      :data="breakListPerson"
      :title="selectDialogPerson.title"
      @change-visible-person="changeVisiblePerson"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入

const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "PCMPSMPROCESSDUTYADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  version: "",
  processId: "",
  processName: "",
  processCode: "",
  businessType: "",
  responsibleRoleList: "",
  leaderRoleList: "",
  enabled: "",
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  details: [
    // {
    //   id: "",
    //   version: "",
    //   dutyId: "",
    //   roleType: 0,
    //   roleId: "",
    //   roleName: "",
    //   enabled: "",
    //   deleted: "",
    //   remarks: "",
    //   createTime: "",
    //   createdUserId: "",
    //   createdUserName: "",
    //   lastUpdateTime: "",
    //   lastUpdatedUserId: "",
    //   lastUpdatedUserName: "",
    // },
  ],
});

/** rules规则 */
const rules = reactive({
  processId: [],
  responsibleRoleList: [],
  leaderRoleList: [],
});

const isValidated = ref(false);
/** 删除行 */
const handleDeleteLeader = (index: any) => {
  tableLeader.value.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};
const handleDeletePerson = (index: any) => {
  tablePerson.value.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details1 = {
  id: "",
  version: "",
  dutyId: "",
  roleType: "",
  roleId: "",
  roleName: "",
  enabled: "",
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
};
const tablePerson = ref([]);
const tableLeader = ref([]);
// watch(
//   () => formData.details,
//   (newVal: any) => {
//     tablePerson.value = [];
//     tableLeader.value = [];
//     formData.details.forEach((item) => {
//       if (item.roleType == 1) {
//         tablePerson.value.push(item);
//       } else if (item.roleType == 2) {
//         tableLeader.value.push(item);
//       }
//     });
//   },
//   { deep: true }
// );

/** 添加行 */
const handleAddLeader = () => {
  // let sondata = JSON.parse(JSON.stringify(details));
  // formData.details.push(sondata);
  selectDialogLeader.value.title = "选择领导人";
  selectDialogLeader.value.visible = true;
  console.log(formData.details);

  if (tableLeader.value.length > 0) {
    getBreakListLeader();
  }
};
const handleAddPerson = () => {
  // let sondata = JSON.parse(JSON.stringify(details));
  // formData.details.push(sondata);
  selectDialogPerson.value.title = "选择责任人";

  selectDialogPerson.value.visible = true;
  if (tablePerson.value.length > 0) {
    getBreakListPerson();
  }
};

const selectDialogLeader = ref({
  visible: false,
  title: "",
});
const changeVisibleLeader = (val: boolean, data: any) => {
  if (data) {
    tableLeader.value = [];
    data.forEach((item) => {
      tableLeader.value.push({
        roleId: item.id,
        roleName: item.roleName,
        roleType: 2,
      });
    });
  }

  selectDialogLeader.value.visible = val;
};

// 新增完返回的数据用于显示选择器
const breakListLeader = ref([]);
const getBreakListLeader = () => {
  breakListLeader.value = [];
  tableLeader.value.forEach((item) => {
    if (item.roleType == 2) {
      breakListLeader.value.push({
        id: item.roleId,
        roleName: item.roleName,
      });
    }
  });
  console.log("breakListLeader", breakListLeader.value);
};

const selectDialogPerson = ref({
  visible: false,
  title: "",
});
const changeVisiblePerson = (val: boolean, data: any) => {
  if (data) {
    tablePerson.value = [];
    data.forEach((item) => {
      tablePerson.value.push({
        roleId: item.id,
        roleName: item.roleName,
        roleType: 1,
      });
    });
  }
  selectDialogPerson.value.visible = val;
};

// 新增完返回的数据用于显示选择器
const breakListPerson = ref([]);
const getBreakListPerson = () => {
  breakListPerson.value = [];
  tablePerson.value.forEach((item) => {
    if (item.roleType == 1) {
      breakListPerson.value.push({
        id: item.roleId,
        roleName: item.roleName,
      });
    }
  });
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
    }
  }
);

const hh = () => {
  tableLeader.value = [];
  tablePerson.value = [];
  console.log("formData.details", formData.details);

  formData.details?.forEach((item) => {
    if (item.roleType == 2) {
      tableLeader.value.push(item);
    } else {
      tablePerson.value.push(item);
    }
  });
};

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [];
  formData.id = "";
  formData.version = "";
  formData.processId = "";
  formData.businessType = "";
  formData.responsibleRoleList = "";
  formData.leaderRoleList = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  tableLeader.value = [];
  tablePerson.value = [];
}

const loading = ref(false);

/** 工序责任设置保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      formData.details = [...tableLeader.value, ...tablePerson.value];
      console.log("formData.details", formData);

      await request({
        url: "/dmpDosPcm/psmprocessduty/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  formData.details = [];
  let sondetails = await request({
    url: "/dmpDosPcm/psmprocessduty/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  sondetails.data.forEach((element) => {
    formData.details.push(element);
  });
  hh();
}

// 获取工艺列表
const processList = ref([]);
const getProcessList = async () => {
  await request({
    url: `mdm/mdmprocess/getList`,
    method: "post",
    data: {},
  }).then((res) => {
    processList.value = res.data;
    console.log("processList.value", processList.value);
  });
};

// 改变工艺路线时
const changeProcess = (e: string) => {
  if (e) {
    processList.value.forEach((item: any) => {
      if (item.id == e) {
        formData.processName = item.processName;
        formData.processCode = item.processCode;
      }
    });
  } else {
    formData.processName = "";
    formData.processCode = "";
  }
};

onMounted(() => {
  getProcessList();
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}

:deep(.el-scrollbar__wrap) {
  max-height: 400px;
  overflow-y: auto;
}
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 140px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
